package com.wmada.toolkit.common.secure;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author will.ma
 * @date 2017/3/12
 */
public class Decrypt {

    private static final Logger LOGGER = LoggerFactory.getLogger(Encrypt.class);

    private Cipher cipher = null;

    public Decrypt(String algorithm, String keyAlgorithm, String password) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(password.getBytes(StandardCharsets.UTF_8), keyAlgorithm);
            cipher = Cipher.getInstance(algorithm);//"算法/模式/补码方式"
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
            LOGGER.error("初始化Decrypt失败", e);
        }
    }

    public Decrypt(String algorithm, String keyAlgorithm, byte[] password) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(password, keyAlgorithm);
            cipher = Cipher.getInstance(algorithm);//"算法/模式/补码方式"
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
            LOGGER.error("初始化Decrypt失败", e);
        }
    }

    public String decrypt(String secret) {
        if (cipher != null && secret != null) {
            try {
                byte[] original = cipher.doFinal(EncodeUtils.base64Decode(secret));
                return new String(original, StandardCharsets.UTF_8);
            } catch (BadPaddingException | IllegalBlockSizeException e) {
                LOGGER.warn("解密字符串失败", e);
                return null;
            }
        } else {
            return null;
        }
    }

    public byte[] decrypt(byte[] data) {
        if (cipher != null && data != null) {
            try {
                return cipher.doFinal(data);
            } catch (BadPaddingException | IllegalBlockSizeException e) {
                LOGGER.warn("解密字符串失败", e);
                return null;
            }
        } else {
            return null;
        }
    }

}
